<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-form ref="questionNewForm" :model="questionNewFormObj" label-width="100px" :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="questionNewFormObj.subjectID" placeholder="请选择学科" @change="subjectIDChange">
            <el-option :label="object.subjectName" :value="object.id" v-for="object in objects" :key="object.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="questionNewFormObj.catalogID" placeholder="请选择目录">
            <el-option :label="directory.directoryName" :value="directory.id" v-for="directory in directorys" :key="directory.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="questionNewFormObj.enterpriseID" placeholder="请选择企业">
            <el-option :label="company.company" :value="company.id" v-for="company in companys" :key="company.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" class="city" prop="province">
          <el-select v-model="questionNewFormObj.province" placeholder="请选择城市" class="province" @change="handleCity">
            <el-option v-for="(item, i) in provinces" :key="i" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="city citys" prop="city">
          <el-select v-model="questionNewFormObj.city" placeholder="请选择市区">
            <el-option v-for="(item1, i1) in cityss" :key="i1" :label="item1" :value="item1"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="questionNewFormObj.direction" placeholder="请选择方向">
            <el-option :label="direction" :value="direction" v-for="(direction, i) in directions" :key="i"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="questionNewFormObj.questionType" @change="chackBox">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="questionNewFormObj.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干----富文本编辑器 -->
        <el-form-item label="题干：" prop="question" class="quill">
          <quill-editor v-model="questionNewFormObj.question" style="height: 300px; margin-bottom: 20px;" class="quill"></quill-editor>
        </el-form-item>
        <!-- 选项-----单选 -->
        <el-form-item label="选项：" v-if="questionNewFormObj.questionType == 1" class="selectOption">
          <el-radio-group v-model="radio" v-for="(opt, i) in questionNewFormObj.options" :key="i" class="radioSelect">
            <el-radio :label="i">
              {{ opt.code }}:
              <el-input v-model.trim="opt.title"></el-input>
            </el-radio>
          </el-radio-group>
          <el-button type="danger" disabled size="mini">+ 增加选项与答案</el-button>
        </el-form-item>
        <!-- 选项-----多选 -->
        <el-form-item label="选项：" v-if="questionNewFormObj.questionType == 2" class="selectOption">
          <el-checkbox-group v-model="checkbox" v-for="(opt, i) in questionNewFormObj.options" :key="i" class="radioSelect">
            <el-checkbox :label="i">
              {{ opt.code }}:
              <el-input v-model.trim="opt.title"></el-input>
            </el-checkbox>
          </el-checkbox-group>
          <el-button type="danger" size="mini" @click="addSelect" :disabled="isDisable">+ 增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input v-model.trim="questionNewFormObj.videoURL" placeholder="请输入解析视频"></el-input>
        </el-form-item>
        <!-- 答案解析----富文本编辑器 -->
        <el-form-item label="答案解析：" prop="answer" class="quill">
          <quill-editor class="quill" v-model="questionNewFormObj.answer" style="height: 300px; margin-bottom: 20px;"></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：">
          <el-input type="textarea" v-model.trim="questionNewFormObj.remarks" placeholder="请输入题目备注"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select v-model="questionNewFormObj.tags" placeholder="请选择试题标签" multiple>
            <el-option :label="tag.tagName" :value="tag.id" v-for="tag in tags" :key="tag.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 提交 -->
        <el-form-item v-if="isAdd">
          <el-button type="primary" @click="submitQuestion">确认提交</el-button>
          <el-button type="default" @click="resetForm()">重置</el-button>
        </el-form-item>
        <!-- 修改 -->
        <el-form-item v-else>
          <el-button type="success" @click="editQuestion">修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { listSubjects } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/directorys.js'
import { listCompanys } from '@/api/hmmm/companys.js'
import { questionsList, questionsListById, addQuestions, editQuestions } from '@/api/hmmm/questions.js'
import { listTags } from '@/api/hmmm/tags.js'
import { provinces, citys } from '@/api/hmmm/citys'
export default {
  data() {
    return {
      questionNewFormObj: {
        questionType: '1',
        difficulty: '1',
        tags: '',
        catalogID: '',
        remarks: '',
        videoURL: '',
        options: [
          { code: 'A', img: '', title: '', isRight: 0 },
          { code: 'B', img: '', title: '', isRight: 0 },
          { code: 'C', img: '', title: '', isRight: 0 },
          { code: 'D', img: '', title: '', isRight: 0 }
        ],
        city: ''
      },
      objects: [],
      directorys: [],
      companys: [],
      directions: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务', '其他'],
      tags: [],
      isDisable: false,
      isAdd: true,
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        city: [{ required: true, message: '请选择市区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请添加题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请添加题干', trigger: 'blur' }]
      },
      provinces: provinces(),
      cityss: [],
      num: 0
    }
  },
  computed: {
    radio: {
      get: function() {
        let ii = null
        this.questionNewFormObj.options.forEach((item, i) => {
          if (item.isRight === 1) {
            ii = i
          }
        })
        return ii
      },
      set(val) {
        console.log(val)
        this.questionNewFormObj.options.forEach((iten, i) => {
          if (val !== i) {
            iten.isRight = 0
          }
        })
        this.questionNewFormObj.options[val].isRight = 1
      }
    },
    checkbox: {
      get: function() {
        let ii = []
        this.questionNewFormObj.options.forEach((item, i) => {
          if (item.isRight === 1) {
            ii.push(i)
          }
        })
        return ii
      },
      set(val) {
        console.log(val)
        if (this.questionNewFormObj.options[val[val.length - 1]].isRight == 1) {
          this.questionNewFormObj.options[val[val.length - 1]].isRight = 0
        } else {
          this.questionNewFormObj.options[val[val.length - 1]].isRight = 1
        }
      }
    }
  },
  watch: {
    checkbox() {
      this.questionNewFormObj.options.forEach((item, i) => {
        if (item.isRight == 1) {
          this.checkbox.push(i)
        }
      })
    },
    // 监听路由变化
    $route(to, from) {
      // console.log(from.query.id)
      // console.log(to.query)
      if (to.query) {
        this.resetForm()
        this.isAdd = true
      }
    }
  },
  mounted() {
    // 获取学科数据
    listSubjects({ pagesize: 30 }).then(data => {
      // console.log(data.data.items)
      this.objects = data.data.items
    })
    // 获取公司、省、市数据
    listCompanys().then(data => {
      // console.log(data);
      this.companys = data.data.items
    })
    if (location.hash.split('?')[1]) {
      this.isAdd = false
      // 说明是修改过来的
      // 说明有参数id传入 是修改状态
      const ids = location.hash.split('?')[1].split('=')[1]
      // 获取修改的信息
      questionsListById(ids).then(async item => {
        // console.log(item.data.subjectID)
        this.questionNewFormObj = item.data
        // 修改前再获取一遍 目录数据 避免回显的数据是id值
        await list({ subjectID: item.data.subjectID }).then(data => {
          this.directorys = data.data.items
        })
        // 获取试题标签数据 subjectID
        await listTags({ subjectID: item.data.subjectID }).then(data => {
          console.log(data.data.items)
          this.tags = data.data.items
          this.questionNewFormObj.tags = [data.data.items[0].tagName]
        })
        this.cityss = citys(item.data.province)
        console.log(item.data)
      })
    } else {
      // 处于添加试题状态
      this.isAdd = true
    }
  },
  activated() {
    // const ids = location.hash.split('?')[1].split('=')[1]
    if (!location.hash.split('?')[1]) {
      this.questionNewFormObj = {
        questionType: '1',
        difficulty: '1',
        tags: '',
        catalogID: '',
        remarks: '',
        videoURL: '',
        options: [
          { code: 'A', img: '', title: '', isRight: 0 },
          { code: 'B', img: '', title: '', isRight: 0 },
          { code: 'C', img: '', title: '', isRight: 0 },
          { code: 'D', img: '', title: '', isRight: 0 }
        ],
        city: ''
      }
    }
  },
  methods: {
    // 学科的change事件
    subjectIDChange() {
      if (this.num >= 1) {
        this.questionNewFormObj.tags = null
        this.questionNewFormObj.catalogID = null
      }
      this.num++
      // 获取目录数据
      list({ subjectID: this.questionNewFormObj.subjectID }).then(data => {
        // console.log(data)
        this.directorys = data.data.items
      })
      // 获取试题标签数据 subjectID
      listTags({ subjectID: this.questionNewFormObj.subjectID }).then(data => {
        // console.log(data.data.items)
        this.tags = data.data.items
      })
    },
    // 获取城市数组
    handleCity(val) {
      this.questionNewFormObj.city = null
      this.cityss = citys(val)
    },
    // 添加复选框的选项的事件
    addSelect() {
      const len = this.questionNewFormObj.options.length
      const obj = {
        code: '',
        title: '',
        img: '',
        isRight: 0
      }
      if (len === 4) {
        obj.code = 'E'
      } else if (len === 5) {
        obj.code = 'F'
      } else if (len === 6) {
        obj.code = 'G'
      }
      this.questionNewFormObj.options.push(obj)
      if (len >= 6) {
        this.isDisable = true
      }
    },
    // 录入试题事件
    submitQuestion() {
      this.$refs.questionNewForm.validate(valid => {
        if (valid) {
          // this.questionNewFormObj
          for (let key in this.questionNewFormObj) {
            if (key === 'tags' || key === 'remarks' || key === 'videoURL') {
              this.questionNewFormObj[key] = this.questionNewFormObj[key].toString()
            }
          }
          // console.log(this.questionNewFormObj);
          addQuestions(this.questionNewFormObj)
            .then(item => {
              // console.log(item);
              this.$message.success('添加成功')
              this.$router.push('/questions/list')
            })
            .catch(err => {
              // console.log(err);
              this.$message.error('添加失败')
            })
        } else {
          this.$message.error('请完成必填项')
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.questionNewForm.resetFields()
      this.directorys = []
      this.questionNewFormObj = {
        questionType: '1',
        difficulty: '1',
        tags: '',
        catalogID: '',
        options: [
          { code: 'A', img: '', title: '', isRight: 0 },
          { code: 'B', img: '', title: '', isRight: 0 },
          { code: 'C', img: '', title: '', isRight: 0 },
          { code: 'D', img: '', title: '', isRight: 0 }
        ],
        city: ''
      }
    },
    // 切换题型
    chackBox() {
      this.questionNewFormObj.options = [
        { code: 'A', img: '', title: '', isRight: 0 },
        { code: 'B', img: '', title: '', isRight: 0 },
        { code: 'C', img: '', title: '', isRight: 0 },
        { code: 'D', img: '', title: '', isRight: 0 }
      ]
    },
    // 修改事件
    editQuestion() {
      this.$refs.questionNewForm.validate(valid => {
        if (valid) {
          for (let key in this.questionNewFormObj) {
            if (key === 'tags') {
              this.questionNewFormObj[key] = this.questionNewFormObj[key].toString()
            }
          }
          editQuestions(this.questionNewFormObj)
            .then(item => {
              this.$message.success('修改成功')
              this.$router.push('/questions/list')
            })
            .catch(err => {
              this.$message.error('修改失败')
            })
        } else {
          this.$message.error('验证失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 20px;
  overflow-y: auto;
  .province {
    margin-right: 10px !important;
  }
  /deep/.quill .el-form-item__content {
    margin-bottom: 70px !important;
  }
  .radioSelect {
    display: block;
  }
  .el-select {
    width: 500px;
  }
  .city {
    display: inline-block;
    .el-select {
      width: 245px;
    }
  }
  .citys {
    /deep/.el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .el-textarea {
    /deep/.el-textarea__inner {
      width: 500px;
      height: 120px;
    }
  }
  .selectOption {
    .radioSelect {
      margin-bottom: 20px;
    }
  }
  .quill {
    /deep/.el-form-item__error {
      top: 114%;
    }
  }
}
</style>
